extends Node2D

@onready var golden_player: CharacterBody2D = $Players/GoldenPlayer
@onready var generate: Node = $Generate
@onready var Menu = $UI/Menu
@onready var gm: MarginContainer = $UI/GM
@onready var ui_interface: Control = $UI/UI_Interface
@onready var ui_inventory: MarginContainer = $UI/UI_Inventory
@onready var inventory_back: Node = $Back/Inventory_Back
@onready var line_edit: LineEdit = $UI/GM/LineEdit
@onready var player_camera: Camera2D = $PlayerCamera

# Called when the node enters the scene tree for the first time.
func _ready():
	ui_inventory.inventory_back = inventory_back
	ui_interface.open_bag.connect(ui_inventory.open_bag)
	ui_interface.died.connect(Menu.show)
	generate.attacks.connect(ui_interface.player_hurted)
	init_hide()
	init_setting()
	pass # Replace with function body.

func init_setting():
	load_game()

func init_hide():
	ui_inventory.hide()
	Menu.hide()
	gm.hide()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
	player_camera.position = golden_player.position
	if Input.is_action_just_pressed("Quit"):
		if Menu.visible:
			Menu.hide()
		else :
			Menu.show()
	if Input.is_action_just_pressed("command"):
		if gm.visible:
			gm.hide()
		else :
			gm.show()


func _notification(what):
	if what == NOTIFICATION_WM_GO_BACK_REQUEST:
		if Menu.visible:
			Menu.hide()
		else :
			Menu.show()


func _on_menu_contined():
	Menu.hide()


func _on_menu_quit():
	save_game()
	queue_free()

## 玩家击杀得分
func _on_player_score():
	ui_interface.get_scores()
	

func _on_info_died() -> void:
	# 提供保存功能
	_on_menu_quit()
	pass # Replace with function body.


## 管理员添加物品
func _on_line_edit_text_submitted(new_text):
	var loadpath = "res://image/anim/" + new_text +".tres"
	inventory_back.add_item(loadpath)
	pass # Replace with function body.

## 保存游戏
func save_game():
	var save_file = FileAccess.open("user://savegame.save", FileAccess.WRITE)
	var save_nodes = get_tree().get_nodes_in_group("Persist")
	# print(save_nodes)
	for node in save_nodes:
		# Now, we can call our save function on each node.
		var node_data = node.call("save_data")
		var json_string = JSON.stringify(node_data)
		save_file.store_line(json_string)
	# print("保存成功")
	
## 载入游戏
func load_game():
	if not FileAccess.file_exists("user://savegame.save"):
		return # Error! We don't have a save to load.
	var save_file = FileAccess.open("user://savegame.save", FileAccess.READ)
	while save_file.get_position() < save_file.get_length():
		var json_string = save_file.get_line()

		# Creates the helper class to interact with JSON
		var json = JSON.new()

		# Check if there is any error while parsing the JSON string, skip in case of failure
		var parse_result = json.parse(json_string)
		if not parse_result == OK:
			print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
			continue

		# Get the data from the JSON object
		var node_data = json.get_data()
		# print(node_data)
		
		for i in get_tree().get_nodes_in_group("Persist"):
			if i.call("get_save_name") == node_data["node"]:
				i.call("load_data",node_data)
				# print("载入成功")
		# print("载入完成")
